/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */

#ifndef BERT_TCPCLIENTSERVER_H
#define BERT_TCPCLIENTSERVER_H

#include "TCPServer.h"
#include "TCPClientThread.h"
#include "debug.h"

class TCPClientServer;

class SuperClient : public TCPClientThreadBuffer
{
	friend class TCPClientServer;
	/**
	 * 先连接游戏主服务器，成功后再建立socket等待玩家连接
	 */
	bool verified;
public:
	/**
	 * Constructor
	 */
	SuperClient() : verified(false)
	{
	}
	/**
	 * Override
	 */
	void msgParse(const void * cmd, unsigned int len)
	{// bert just for test
		NullBaseCmd * pCmd = (NullBaseCmd *)cmd;

		switch( pCmd->byCmd)
		{
			case LOGIN_CMD:
				switch(pCmd->byParam)
				{
					case RETURN_LOGIN_PARAM_SS:
						{
							ReturnLoginCmd * p = (ReturnLoginCmd *)pCmd;
							if ( p->state != 0 )
								this->verified = true;
							return ;
						}
					default:
						return ;
				}
			default:
				return ;
		}
		return ;
	}
	/**
	 * Thread
	 */
	void run();
};

class TCPClientServer : public TCPServer
{
protected:
	/**
	 * The client thread
	 */
	SuperClient superClient;
	//std::string superIP;
	//unsigned short superPort;
	/**
	 * The unique clientserver
	 */
	static TCPClientServer * instance;
	/**
	 * Create socket and connect to servip, then sendlogincmd
	 */
	bool connect( const char * servip, const unsigned short port);
	/**
	 * Connect to super first, then create listen socket
	 */
	virtual bool init();
	/**
	 * 我是什么类型的服务器
	 */
	unsigned int serverType;
	/**
	 * Request login, must be override
	 */
	virtual bool sendLoginCmd() = 0;
public:
	/**
	 * Constructor
	 */
	TCPClientServer() 
	{
		instance = this;
	}
	/**
	 * Destructor
	 */
	virtual ~TCPClientServer();
	/**
	 * Get the unique clientserver
	 */
	static TCPClientServer * serverInstance()
	{
		return instance;
	}
	/**
	 * 解析服务器管理器的消息 timetick will call it
	 */
	void doCmd()
	{
		superClient.doCmd();
	}
	/**
	 * Delete listen socket, stop superclient thread
	 */
	void recycle();
};

#endif

